// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// ███╗   ██╗ ██████╗ ████████╗██╗ ██████╗███████╗
// ████╗  ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝
// ██╔██╗ ██║██║   ██║   ██║   ██║██║     █████╗
// ██║╚██╗██║██║   ██║   ██║   ██║██║     ██╔══╝
// ██║ ╚████║╚██████╔╝   ██║   ██║╚██████╗███████╗
// ╚═╝  ╚═══╝ ╚═════╝    ╚═╝   ╚═╝ ╚═════╝╚══════╝
// ------------------------------------------------
//
// This file is automatically generated.
// Please do not edit these files manually.
//
// ------------------------------------------------

#nullable restore

using Elastic.Clients.Elasticsearch.Fluent;
using Elastic.Clients.Elasticsearch.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Elastic.Clients.Elasticsearch.QueryDsl;

[JsonConverter(typeof(SparseVectorQueryConverter))]
public sealed partial class SparseVectorQuery
{
	internal SparseVectorQuery(string variantName, object variant)
	{
		if (variantName is null)
			throw new ArgumentNullException(nameof(variantName));
		if (variant is null)
			throw new ArgumentNullException(nameof(variant));
		if (string.IsNullOrWhiteSpace(variantName))
			throw new ArgumentException("Variant name must not be empty or whitespace.");
		VariantName = variantName;
		Variant = variant;
	}

	internal object Variant { get; }
	internal string VariantName { get; }

	public static SparseVectorQuery InferenceId(Elastic.Clients.Elasticsearch.Id id) => new SparseVectorQuery("inference_id", id);

	/// <summary>
	/// <para>
	/// Floating point number used to decrease or increase the relevance scores of the query.
	/// Boost values are relative to the default value of 1.0.
	/// A boost value between 0 and 1.0 decreases the relevance score.
	/// A value greater than 1.0 increases the relevance score.
	/// </para>
	/// </summary>
	[JsonInclude, JsonPropertyName("boost")]
	public float? Boost { get; set; }

	/// <summary>
	/// <para>
	/// The name of the field that contains the token-weight pairs to be searched against.
	/// This field must be a mapped sparse_vector field.
	/// </para>
	/// </summary>
	[JsonInclude, JsonPropertyName("field")]
	public Elastic.Clients.Elasticsearch.Field Field { get; set; }

	/// <summary>
	/// <para>
	/// Whether to perform pruning, omitting the non-significant tokens from the query to improve query performance.
	/// If prune is true but the pruning_config is not specified, pruning will occur but default values will be used.
	/// Default: false
	/// </para>
	/// </summary>
	[JsonInclude, JsonPropertyName("prune")]
	public bool? Prune { get; set; }

	/// <summary>
	/// <para>
	/// Optional pruning configuration.
	/// If enabled, this will omit non-significant tokens from the query in order to improve query performance.
	/// This is only used if prune is set to true.
	/// If prune is set to true but pruning_config is not specified, default values will be used.
	/// </para>
	/// </summary>
	[JsonInclude, JsonPropertyName("pruning_config")]
	public Elastic.Clients.Elasticsearch.QueryDsl.TokenPruningConfig? PruningConfig { get; set; }

	/// <summary>
	/// <para>
	/// The query text you want to use for search.
	/// If inference_id is specified, query must also be specified.
	/// </para>
	/// </summary>
	[JsonInclude, JsonPropertyName("query")]
	public string? Query { get; set; }
	[JsonInclude, JsonPropertyName("_name")]
	public string? QueryName { get; set; }

	public bool TryGet<T>([NotNullWhen(true)] out T? result) where T : class
	{
		result = default;
		if (Variant is T variant)
		{
			result = variant;
			return true;
		}

		return false;
	}
}

internal sealed partial class SparseVectorQueryConverter : JsonConverter<SparseVectorQuery>
{
	public override SparseVectorQuery Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
	{
		if (reader.TokenType != JsonTokenType.StartObject)
		{
			throw new JsonException("Expected start token.");
		}

		object? variantValue = default;
		string? variantNameValue = default;
		float? boostValue = default;
		Elastic.Clients.Elasticsearch.Field fieldValue = default;
		bool? pruneValue = default;
		Elastic.Clients.Elasticsearch.QueryDsl.TokenPruningConfig? pruningConfigValue = default;
		string? queryValue = default;
		string? queryNameValue = default;
		while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
		{
			if (reader.TokenType != JsonTokenType.PropertyName)
			{
				throw new JsonException("Expected a property name token.");
			}

			if (reader.TokenType != JsonTokenType.PropertyName)
			{
				throw new JsonException("Expected a property name token representing the name of an Elasticsearch field.");
			}

			var propertyName = reader.GetString();
			reader.Read();
			if (propertyName == "boost")
			{
				boostValue = JsonSerializer.Deserialize<float?>(ref reader, options);
				continue;
			}

			if (propertyName == "field")
			{
				fieldValue = JsonSerializer.Deserialize<Elastic.Clients.Elasticsearch.Field>(ref reader, options);
				continue;
			}

			if (propertyName == "prune")
			{
				pruneValue = JsonSerializer.Deserialize<bool?>(ref reader, options);
				continue;
			}

			if (propertyName == "pruning_config")
			{
				pruningConfigValue = JsonSerializer.Deserialize<Elastic.Clients.Elasticsearch.QueryDsl.TokenPruningConfig?>(ref reader, options);
				continue;
			}

			if (propertyName == "query")
			{
				queryValue = JsonSerializer.Deserialize<string?>(ref reader, options);
				continue;
			}

			if (propertyName == "_name")
			{
				queryNameValue = JsonSerializer.Deserialize<string?>(ref reader, options);
				continue;
			}

			if (propertyName == "inference_id")
			{
				variantValue = JsonSerializer.Deserialize<Elastic.Clients.Elasticsearch.Id?>(ref reader, options);
				variantNameValue = propertyName;
				continue;
			}

			throw new JsonException($"Unknown property name '{propertyName}' received while deserializing the 'SparseVectorQuery' from the response.");
		}

		var result = new SparseVectorQuery(variantNameValue, variantValue);
		result.Boost = boostValue;
		result.Field = fieldValue;
		result.Prune = pruneValue;
		result.PruningConfig = pruningConfigValue;
		result.Query = queryValue;
		result.QueryName = queryNameValue;
		return result;
	}

	public override void Write(Utf8JsonWriter writer, SparseVectorQuery value, JsonSerializerOptions options)
	{
		writer.WriteStartObject();
		if (value.Boost.HasValue)
		{
			writer.WritePropertyName("boost");
			writer.WriteNumberValue(value.Boost.Value);
		}

		if (value.Field is not null)
		{
			writer.WritePropertyName("field");
			JsonSerializer.Serialize(writer, value.Field, options);
		}

		if (value.Prune.HasValue)
		{
			writer.WritePropertyName("prune");
			writer.WriteBooleanValue(value.Prune.Value);
		}

		if (value.PruningConfig is not null)
		{
			writer.WritePropertyName("pruning_config");
			JsonSerializer.Serialize(writer, value.PruningConfig, options);
		}

		if (!string.IsNullOrEmpty(value.Query))
		{
			writer.WritePropertyName("query");
			writer.WriteStringValue(value.Query);
		}

		if (!string.IsNullOrEmpty(value.QueryName))
		{
			writer.WritePropertyName("_name");
			writer.WriteStringValue(value.QueryName);
		}

		if (value.VariantName is not null && value.Variant is not null)
		{
			writer.WritePropertyName(value.VariantName);
			switch (value.VariantName)
			{
				case "inference_id":
					JsonSerializer.Serialize<Elastic.Clients.Elasticsearch.Id>(writer, (Elastic.Clients.Elasticsearch.Id)value.Variant, options);
					break;
			}
		}

		writer.WriteEndObject();
	}
}

public sealed partial class SparseVectorQueryDescriptor<TDocument> : SerializableDescriptor<SparseVectorQueryDescriptor<TDocument>>
{
	internal SparseVectorQueryDescriptor(Action<SparseVectorQueryDescriptor<TDocument>> configure) => configure.Invoke(this);

	public SparseVectorQueryDescriptor() : base()
	{
	}

	private bool ContainsVariant { get; set; }
	private string ContainedVariantName { get; set; }
	private object Variant { get; set; }
	private Descriptor Descriptor { get; set; }

	private SparseVectorQueryDescriptor<TDocument> Set<T>(Action<T> descriptorAction, string variantName) where T : Descriptor
	{
		ContainedVariantName = variantName;
		ContainsVariant = true;
		var descriptor = (T)Activator.CreateInstance(typeof(T), true);
		descriptorAction?.Invoke(descriptor);
		Descriptor = descriptor;
		return Self;
	}

	private SparseVectorQueryDescriptor<TDocument> Set(object variant, string variantName)
	{
		Variant = variant;
		ContainedVariantName = variantName;
		ContainsVariant = true;
		return Self;
	}

	private float? BoostValue { get; set; }
	private Elastic.Clients.Elasticsearch.Field FieldValue { get; set; }
	private bool? PruneValue { get; set; }
	private Elastic.Clients.Elasticsearch.QueryDsl.TokenPruningConfig? PruningConfigValue { get; set; }
	private string? QueryValue { get; set; }
	private string? QueryNameValue { get; set; }

	/// <summary>
	/// <para>
	/// Floating point number used to decrease or increase the relevance scores of the query.
	/// Boost values are relative to the default value of 1.0.
	/// A boost value between 0 and 1.0 decreases the relevance score.
	/// A value greater than 1.0 increases the relevance score.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor<TDocument> Boost(float? boost)
	{
		BoostValue = boost;
		return Self;
	}

	/// <summary>
	/// <para>
	/// The name of the field that contains the token-weight pairs to be searched against.
	/// This field must be a mapped sparse_vector field.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor<TDocument> Field(Elastic.Clients.Elasticsearch.Field field)
	{
		FieldValue = field;
		return Self;
	}

	/// <summary>
	/// <para>
	/// The name of the field that contains the token-weight pairs to be searched against.
	/// This field must be a mapped sparse_vector field.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor<TDocument> Field<TValue>(Expression<Func<TDocument, TValue>> field)
	{
		FieldValue = field;
		return Self;
	}

	/// <summary>
	/// <para>
	/// The name of the field that contains the token-weight pairs to be searched against.
	/// This field must be a mapped sparse_vector field.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor<TDocument> Field(Expression<Func<TDocument, object>> field)
	{
		FieldValue = field;
		return Self;
	}

	/// <summary>
	/// <para>
	/// Whether to perform pruning, omitting the non-significant tokens from the query to improve query performance.
	/// If prune is true but the pruning_config is not specified, pruning will occur but default values will be used.
	/// Default: false
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor<TDocument> Prune(bool? prune = true)
	{
		PruneValue = prune;
		return Self;
	}

	/// <summary>
	/// <para>
	/// Optional pruning configuration.
	/// If enabled, this will omit non-significant tokens from the query in order to improve query performance.
	/// This is only used if prune is set to true.
	/// If prune is set to true but pruning_config is not specified, default values will be used.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor<TDocument> PruningConfig(Elastic.Clients.Elasticsearch.QueryDsl.TokenPruningConfig? pruningConfig)
	{
		PruningConfigValue = pruningConfig;
		return Self;
	}

	/// <summary>
	/// <para>
	/// The query text you want to use for search.
	/// If inference_id is specified, query must also be specified.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor<TDocument> Query(string? query)
	{
		QueryValue = query;
		return Self;
	}

	public SparseVectorQueryDescriptor<TDocument> QueryName(string? queryName)
	{
		QueryNameValue = queryName;
		return Self;
	}

	public SparseVectorQueryDescriptor<TDocument> InferenceId(Elastic.Clients.Elasticsearch.Id id) => Set(id, "inference_id");

	protected override void Serialize(Utf8JsonWriter writer, JsonSerializerOptions options, IElasticsearchClientSettings settings)
	{
		writer.WriteStartObject();
		if (BoostValue.HasValue)
		{
			writer.WritePropertyName("boost");
			writer.WriteNumberValue(BoostValue.Value);
		}

		if (FieldValue is not null)
		{
			writer.WritePropertyName("field");
			JsonSerializer.Serialize(writer, FieldValue, options);
		}

		if (PruneValue.HasValue)
		{
			writer.WritePropertyName("prune");
			writer.WriteBooleanValue(PruneValue.Value);
		}

		if (PruningConfigValue is not null)
		{
			writer.WritePropertyName("pruning_config");
			JsonSerializer.Serialize(writer, PruningConfigValue, options);
		}

		if (!string.IsNullOrEmpty(QueryValue))
		{
			writer.WritePropertyName("query");
			writer.WriteStringValue(QueryValue);
		}

		if (!string.IsNullOrEmpty(QueryNameValue))
		{
			writer.WritePropertyName("_name");
			writer.WriteStringValue(QueryNameValue);
		}

		if (!string.IsNullOrEmpty(ContainedVariantName))
		{
			writer.WritePropertyName(ContainedVariantName);
			if (Variant is not null)
			{
				JsonSerializer.Serialize(writer, Variant, Variant.GetType(), options);
				writer.WriteEndObject();
				return;
			}

			JsonSerializer.Serialize(writer, Descriptor, Descriptor.GetType(), options);
		}

		writer.WriteEndObject();
	}
}

public sealed partial class SparseVectorQueryDescriptor : SerializableDescriptor<SparseVectorQueryDescriptor>
{
	internal SparseVectorQueryDescriptor(Action<SparseVectorQueryDescriptor> configure) => configure.Invoke(this);

	public SparseVectorQueryDescriptor() : base()
	{
	}

	private bool ContainsVariant { get; set; }
	private string ContainedVariantName { get; set; }
	private object Variant { get; set; }
	private Descriptor Descriptor { get; set; }

	private SparseVectorQueryDescriptor Set<T>(Action<T> descriptorAction, string variantName) where T : Descriptor
	{
		ContainedVariantName = variantName;
		ContainsVariant = true;
		var descriptor = (T)Activator.CreateInstance(typeof(T), true);
		descriptorAction?.Invoke(descriptor);
		Descriptor = descriptor;
		return Self;
	}

	private SparseVectorQueryDescriptor Set(object variant, string variantName)
	{
		Variant = variant;
		ContainedVariantName = variantName;
		ContainsVariant = true;
		return Self;
	}

	private float? BoostValue { get; set; }
	private Elastic.Clients.Elasticsearch.Field FieldValue { get; set; }
	private bool? PruneValue { get; set; }
	private Elastic.Clients.Elasticsearch.QueryDsl.TokenPruningConfig? PruningConfigValue { get; set; }
	private string? QueryValue { get; set; }
	private string? QueryNameValue { get; set; }

	/// <summary>
	/// <para>
	/// Floating point number used to decrease or increase the relevance scores of the query.
	/// Boost values are relative to the default value of 1.0.
	/// A boost value between 0 and 1.0 decreases the relevance score.
	/// A value greater than 1.0 increases the relevance score.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor Boost(float? boost)
	{
		BoostValue = boost;
		return Self;
	}

	/// <summary>
	/// <para>
	/// The name of the field that contains the token-weight pairs to be searched against.
	/// This field must be a mapped sparse_vector field.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor Field(Elastic.Clients.Elasticsearch.Field field)
	{
		FieldValue = field;
		return Self;
	}

	/// <summary>
	/// <para>
	/// The name of the field that contains the token-weight pairs to be searched against.
	/// This field must be a mapped sparse_vector field.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor Field<TDocument, TValue>(Expression<Func<TDocument, TValue>> field)
	{
		FieldValue = field;
		return Self;
	}

	/// <summary>
	/// <para>
	/// The name of the field that contains the token-weight pairs to be searched against.
	/// This field must be a mapped sparse_vector field.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor Field<TDocument>(Expression<Func<TDocument, object>> field)
	{
		FieldValue = field;
		return Self;
	}

	/// <summary>
	/// <para>
	/// Whether to perform pruning, omitting the non-significant tokens from the query to improve query performance.
	/// If prune is true but the pruning_config is not specified, pruning will occur but default values will be used.
	/// Default: false
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor Prune(bool? prune = true)
	{
		PruneValue = prune;
		return Self;
	}

	/// <summary>
	/// <para>
	/// Optional pruning configuration.
	/// If enabled, this will omit non-significant tokens from the query in order to improve query performance.
	/// This is only used if prune is set to true.
	/// If prune is set to true but pruning_config is not specified, default values will be used.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor PruningConfig(Elastic.Clients.Elasticsearch.QueryDsl.TokenPruningConfig? pruningConfig)
	{
		PruningConfigValue = pruningConfig;
		return Self;
	}

	/// <summary>
	/// <para>
	/// The query text you want to use for search.
	/// If inference_id is specified, query must also be specified.
	/// </para>
	/// </summary>
	public SparseVectorQueryDescriptor Query(string? query)
	{
		QueryValue = query;
		return Self;
	}

	public SparseVectorQueryDescriptor QueryName(string? queryName)
	{
		QueryNameValue = queryName;
		return Self;
	}

	public SparseVectorQueryDescriptor InferenceId(Elastic.Clients.Elasticsearch.Id id) => Set(id, "inference_id");

	protected override void Serialize(Utf8JsonWriter writer, JsonSerializerOptions options, IElasticsearchClientSettings settings)
	{
		writer.WriteStartObject();
		if (BoostValue.HasValue)
		{
			writer.WritePropertyName("boost");
			writer.WriteNumberValue(BoostValue.Value);
		}

		if (FieldValue is not null)
		{
			writer.WritePropertyName("field");
			JsonSerializer.Serialize(writer, FieldValue, options);
		}

		if (PruneValue.HasValue)
		{
			writer.WritePropertyName("prune");
			writer.WriteBooleanValue(PruneValue.Value);
		}

		if (PruningConfigValue is not null)
		{
			writer.WritePropertyName("pruning_config");
			JsonSerializer.Serialize(writer, PruningConfigValue, options);
		}

		if (!string.IsNullOrEmpty(QueryValue))
		{
			writer.WritePropertyName("query");
			writer.WriteStringValue(QueryValue);
		}

		if (!string.IsNullOrEmpty(QueryNameValue))
		{
			writer.WritePropertyName("_name");
			writer.WriteStringValue(QueryNameValue);
		}

		if (!string.IsNullOrEmpty(ContainedVariantName))
		{
			writer.WritePropertyName(ContainedVariantName);
			if (Variant is not null)
			{
				JsonSerializer.Serialize(writer, Variant, Variant.GetType(), options);
				writer.WriteEndObject();
				return;
			}

			JsonSerializer.Serialize(writer, Descriptor, Descriptor.GetType(), options);
		}

		writer.WriteEndObject();
	}
}